// Node 标准库的封装，有一定业务耦合
const fs = require('fs')

function writeJSONFileSync(filePath, o = {}) {
  fs.writeFileSync(filePath, JSON.stringify(o, null, 2), 'utf8')
}

function readJSONFileSync(filePath, options = 'utf8') {
  const o = {}

  try {
    return JSON.parse(fs.readFileSync(filePath, options))
  } catch (e) {
    if (e instanceof SyntaxError) {
      console.log('JSON 解析失败，请检查文件 "' + filePath + '" 内容')
      console.log(e)
    }
  }

  return o
}

function existsJSONSync(filePath, autoInit) {
  const isExists = fs.existsSync(filePath)
  !isExists && autoInit && writeJSONFileSync(filePath, {})

  return isExists
}

const { exec } = require('child_process')
const os = require('os')

function openFile(filePath, debug = false) {
  let command

  // 根据操作系统选择命令
  if (os.platform() === 'darwin') {
    // Mac 使用 'open' 命令
    command = `open ${filePath}`
  } else if (os.platform() === 'win32') {
    // Windows 使用 'start' 命令
    command = `start ${filePath}`
  } else {
    console.error('Unsupported operating system')
    return
  }

  // 执行命令
  exec(command, (error, stdout, stderr) => {
    if (error) {
      debug && console.error(`Error: ${error.message}`)
      return
    }

    if (stderr) {
      debug && console.error(`Stderr: ${stderr}`)
      return
    }

    debug && console.log(`File opened successfully: ${stdout}`)
  })
}

module.exports = {
  readJSONFileSync,
  writeJSONFileSync,
  existsJSONSync,
  openFile
}
